package com.scalar.chiptrack.externalusers.actions;

import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.users.User;
import com.scalar.chiptrack.externalusers.dao.ExternalUserSetupDAO;
import com.scalar.chiptrack.externalusers.forms.ExternalUserLoginForm;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.ScalarException;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForm;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.*;

public class ExternalUserLoginAction extends ChipTrackAction {

    public ActionForward execute (ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception
    {

        User user = null;
        HttpSession session = request.getSession();

        ExternalUserLoginForm externalUserLoginForm = ( ExternalUserLoginForm ) form;

        String userId = externalUserLoginForm.getUserId();
        String password = externalUserLoginForm.getPassword();
        HashMap errors = new HashMap();
        request.setAttribute( "ps", request.getParameter("ps") );
        request.setAttribute( "cstKey", request.getParameter("cstKey") );
        if ( request.getParameter("actionLogin") == null )
        {
            return (mapping.findForward ("failure"));
        }
        if ((userId == null) || (userId.trim().length() == 0)) 
        {
            errors.put ("User Name", "User ID required");
        }
        if ((password == null) || (password.length() == 0)) 
        {
            errors.put ("Password", "Password required");
        }

        if (errors.isEmpty() == false) 
        {
            request.setAttribute(SessionKeys.ERROR_MESSAGES, errors);
            return (mapping.findForward ("failure"));
        }

        try
        {
            int packingSlipVendorId = -1;
            int customerShippingId  = -1;
            // load user from database (includes password verification)
            user = ExternalUserSetupDAO.loadExternalUser (userId, password);

            if ( user.getExpiresOn() != null && user.getExpiresOn().trim().length() > 0  )
            {
                StringTokenizer st = new StringTokenizer (user.getExpiresOn().substring(0,10) , "-");
                int year = Integer.parseInt (st.nextToken());
                int month = Integer.parseInt (st.nextToken());
                int day = Integer.parseInt (st.nextToken());
                Date expOnDate = new GregorianCalendar(year, month - 1 , day ).getTime();
                Calendar nowCal = new GregorianCalendar();
                nowCal.setTime(new Date());
                Date presentDate = new GregorianCalendar(nowCal.get(Calendar.YEAR), nowCal.get(Calendar.MONTH), nowCal.get(Calendar.DATE)).getTime();
                if( presentDate.compareTo( expOnDate ) > 0 )
                {
                    errors.put ("Login Failed", "Login Expired");
                    request.setAttribute(SessionKeys.ERROR_MESSAGES, errors);
                    return (mapping.findForward ("failure"));
                }
            }

            if( request.getParameter("ps") != null )
            {
                try
                {
                    customerShippingId  = Integer.parseInt( request.getParameter("ps") );
                }
                catch(NumberFormatException e){}
            }

            packingSlipVendorId = ExternalUserSetupDAO.getPackingSlipVendorId( null, customerShippingId );

            if( user.getVendorId() != packingSlipVendorId )
            {
                errors.put ("Login Failed", "User not associated with this Packing Slip");
                request.setAttribute(SessionKeys.ERROR_MESSAGES, errors);
                return (mapping.findForward ("failure"));
            }
            session.setAttribute ( SessionKeys.EXT_USER_KEY , user );
            // Remove the User Object From Session if present
            session.removeAttribute( SessionKeys.USER_KEY );
        }
        catch (ScalarException se) 
		{
            String error = "Internal Server Error";
            String exceptionMessage = se.getRootCause().getMessage();

            if (exceptionMessage.indexOf("Invalid password") != -1) 
            {
                error = "Invalid Password";
            }
            else if (exceptionMessage.indexOf("Invalid user id") != -1) 
            {
                error = "Invalid User ID";
            }
            errors = new HashMap();
            errors.put ( error, "Login Failed" );
            request.setAttribute ( SessionKeys.ERROR_MESSAGES, errors );
        }
        if (errors.isEmpty())
        {
            String returnPath = (String) session.getAttribute (SessionKeys.SOURCE_PAGE_KEY);
            session.removeAttribute (SessionKeys.SOURCE_PAGE_KEY);
            if ( returnPath == null )
            {
                return mapping.findForward("success");
            }
            else
            {
                return new ActionForward (returnPath);
            }
        }
        else
        {
            return mapping.findForward("failure");
        }
    }
}